﻿using Authentication.Data.Repository;
using Authentication.Model.Interface;
using Authentication.Model.Model;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Authentication.Provider
{
    public class GroupProvider : GenericProvider, IGroupProvider
    {
        public IEnumerable<ApplicationGroup> SearchGroups(out int totalRecord, Guid applicationKey, string name = null, int pagesize = 0, int pageindex = 0)
        {
            var appkey = applicationKey.ToString().ToUpper();
            var querry = from o in repository.Groups where o.ApplicationKey.ToUpper() == appkey select o;
            querry = querry.OrderBy(o => o.GroupId) as IQueryable<ApplicationGroup>;
            if (!string.IsNullOrWhiteSpace(name))
            {
                querry = querry.Where(x => x.GroupNameEnglish.ToUpper().Contains(name.Trim().ToUpper()) || x.GroupNameLocal.ToUpper().Contains(name.Trim().ToUpper()));
            }

            totalRecord = querry.Count();
            if (pagesize > 0 && pageindex >= 0)
            {
                querry = querry.Skip(pageindex * pagesize).Take(pagesize);
            }

            return querry.ToList();
        }


        public bool Update(ApplicationGroup obj)
        {
            try
            {
                var appKey = obj.ApplicationKey.ToUpper();
                var GroupId = obj.GroupId;
                var GroupChecked = repository.FindOne<ApplicationGroup>(x => x.GroupId == GroupId && x.ApplicationKey.ToUpper() == appKey);
                if (GroupChecked == null) return false;

                GroupChecked.Active = obj.Active;
                GroupChecked.GroupNameEnglish = obj.GroupNameEnglish;
                GroupChecked.GroupNameLocal = obj.GroupNameLocal;
                GroupChecked.Description = obj.Description;

                repository.UnitOfWork.SaveChanges();
                return true;
            }
            catch
            {
                return false;
            }
        }

        public bool Delete(Guid applicationKey, string GroupId)
        {
            try
            {
                var appKey = applicationKey.ToString().ToUpper();
                repository.Delete<ApplicationGroup>(x => x.GroupId == GroupId && x.ApplicationKey.ToUpper() == appKey);
                repository.UnitOfWork.SaveChanges();
                return true;
            }
            catch
            {
                return false;
            }
        }


        public bool Add(ApplicationGroup obj)
        {
            try
            {
                repository.Groups.Add(obj);
                repository.UnitOfWork.SaveChanges();
                return true;
            }
            catch
            {
                return false;
            }
        }
    }
}
